package com.imesne.office.excel.model;

import com.imesne.office.excel.exception.OfficeException;
import org.apache.commons.lang3.StringUtils;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by liyd on 17/6/30.
 */
public class ExcelBook extends ExcelProperties {

    /**
     * excel sheet
     */
    private Map<Integer, ExcelSheet> excelSheets;

    /**
     * sheet号，新建不指定时内部自动生成
     */
    private int sheetNum;

    public ExcelBook() {
        excelSheets = new LinkedHashMap<>();
        sheetNum = 1;
    }

    /**
     * 添加一个sheet
     *
     * @param excelSheet
     */
    public void addSheet(ExcelSheet excelSheet) {
        if (excelSheet.getSheetNum() == null) {
            throw new OfficeException("sheetNum不能为空");
        }
        excelSheets.put(excelSheet.getSheetNum(), excelSheet);
    }

    public ExcelSheet getFirstExcelSheet() {
        return this.excelSheets.values().iterator().next();
    }

    public Collection<ExcelSheet> getExcelSheets() {
        return this.excelSheets.values();
    }

    public ExcelSheet getExcelSheet(String sheetName) {
        Collection<ExcelSheet> excelSheets = this.getExcelSheets();
        for (ExcelSheet excelSheet : excelSheets) {
            if (StringUtils.equals(sheetName, excelSheet.getSheetName())) {
                return excelSheet;
            }
        }
        return null;
    }

    public ExcelSheet getExcelSheet(int sheetNum) {
        return this.excelSheets.get(sheetNum);
    }

    public ExcelSheet createSheet(String sheetName) {
        ExcelSheet excelSheet = new ExcelSheet(sheetName);
        excelSheet.setSheetNum(sheetNum++);
        this.addSheet(excelSheet);
        return excelSheet;
    }

    public ExcelSheet createSheet() {
        return this.createSheet(null);
    }

    /**
     * 创建一个sheet，指定sheetNum，一般在追加内容时使用
     *
     * @param sheetNum
     * @return
     */
    public ExcelSheet createSheet(int sheetNum) {
        ExcelSheet excelSheet = new ExcelSheet();
        excelSheet.setSheetNum(sheetNum);
        this.addSheet(excelSheet);
        return excelSheet;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (ExcelSheet excelSheet : getExcelSheets()) {
            sb.append("sheet >: ")
                    .append(excelSheet)
                    .append(System.lineSeparator());
        }
        return sb.toString();
    }
}
